import UI from "../common/UI";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Piece extends cc.Component {
    public row: number
    public col: number

    private _trueRow: number
    private _trueCol: number

    private _canMove: boolean = true

    private label: cc.Label = null

    protected onLoad(): void {
        this.label = UI.GetComponent(this.node, 'label', cc.Label)
    }

    get trueRow(): number {
        return this._trueRow
    }

    get trueCol(): number {
        return this._trueCol
    }

    get text() {
        return this.label.string
    }

    get canMove() {
        return this._canMove
    }

    public forbidMove() {
        this._canMove = false
        this.node.color = cc.color(0, 23, 227)
    }

    public init(x: number, y: number, text: string) {
        this.row = x
        this.col = y
        this._trueRow = x
        this._trueCol = y
        this.label.string = text
    }

    public black() {
        this.node.color = cc.color(0, 0, 0)
        this.node.opacity = 152
        for (let childIdx = 0; childIdx < this.node.childrenCount; childIdx++) {
            this.node.children[childIdx].opacity = 152
        }
    }

    public canExchange(piece: Piece) {
        return (this.row == piece.row && Math.abs(this.col - piece.col) == 1) ||
            (this.col == piece.col && Math.abs(this.row - piece.row) == 1)
    }

    public exchange(piece: Piece, isMove: boolean = true) {
        if ((isMove && !this.canExchange(piece)) || !this.canMove) {
            return false
        }

        [this.row, piece.row] = [piece.row, this.row];
        [this.col, piece.col] = [piece.col, this.col];
        [this.node.position, piece.node.position] =
            [piece.node.position, this.node.position]
        return true
    }

    public orderIdx(colCount: number) {
        return this.trueRow * colCount + this.trueCol
    }
}
